<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="deps" :props="defaultProps">
        <template v-slot="{data}">
          <el-row type="flex" align="middle" style="width:100%;height:40px">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4" style="text-align:right">
              <span class="gly">{{ data.managerName }}</span>
              <!-- 下拉菜单 -->
              <el-dropdown @command="depHanld($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门
                  </el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <Form ref="getDep" :show-dialog.sync="showDialog" :newdeps="newdeps" :current-node-id="currentNodeId" @updatwDeps="updatwDeps" />
  </div>
</template>
<script>
import { getDepartments, delDept } from '@/api/department'
import { transListToTree } from '@/utils'
import Form from './addForm/Form.vue'
export default {
  name: 'Department',
  components: {
    Form
  },
  data() {
    return {
      deps: [],
      newdeps: [],
      currentNodeId: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false
    }
  },
  async created() {
    // const res = await getDepartments()
    this.getDepartments()
    // console.log(res)
  },
  methods: {
    async getDepartments() {
      const res = await getDepartments()
      console.log(res)
      this.deps = transListToTree(res, 0)
      console.log(this.deps)
      this.newdeps = res
    },
    depHanld(command, id) {
      // console.log(111)
      console.log(command)
      if (command === 'add') {
        this.showDialog = true
        this.currentNodeId = id
        // console.log(this.currentNodeId)
      } else if (command === 'edit') {
        this.showDialog = true
        // 更新props是异步的，也就是下面这个流向子级是异步的
        // 但是父组件调用子组件的方法来获取数据是同步的，所以加上nextTick
        this.currentNodeId = id
        this.$nextTick(() => {
          this.$refs.getDep.getDepDetail()
        })
      } else {
        this.$confirm('确定要删除吗', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(async() => {
          await delDept(id)
          this.$message.success('删除成功')
          this.getDepartments()
        })
      }
    },
    updatwDeps() {
      this.getDepartments()
    }
  }
}
</script>
<style lang="scss" scoped>
.gly{
  width: 50px;
  margin: 10px;
  display: inline-block
}
</style>
